package com.yunji.base.business;

import com.yunji.base.domain.BelongDO;
import com.yunji.base.domain.ShortCutMenuDO;
import com.yunji.base.params.BelongPageParam;
import com.yunji.base.params.BelongSearchParam;
import com.yunji.base.service.BelongService;
import com.yunji.base.service.ShortCutService;
import com.yunji.base.vo.ShortCutVO;
import com.yunji.common.base.BaseBusiness;
import com.yunji.common.constant.LogicCode;
import com.yunji.common.enums.common.UserType;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.storage.vo.TreeVO;
import com.yunji.system.service.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Package com.yunji.web.belong.business
 * FileName:	BelongBusiness.java
 * Copyright:	Copyright © 2024 All Rights Reserved
 * Company:		云集互联
 * @version: 1.0
 * @since: JDK 1.8.0_202
 * Create at:   2024-08-15 17:58:06.874
 * Description:
 * 所属信息业务处理
 * Modification History:
 * Author					Date						Version			Description
 * --------------------------------------------------------------------------------
 * HuaAo				2024-08-15 17:58:06			1.0				1.0 Version
 */
@Component
public class BelongBusiness extends BaseBusiness {
    @Resource
    BelongService belongService;

    @Resource
    TokenService tokenService;

    @Resource
    ShortCutService shortCutService;

    /**
     * @Title search
     * @Intro 查询所属信息列表
     * @Date 2024-08-15 17:58:06.881
     * @param    belong 所属信息参数
     * @return List<Belong> 所属信息列表
     */
//    public List<Belong> search(Belong belong)
//    {
//        return belongService.search(belong);
//    }

    /**
     * @param id 所属信息ID
     * @return Belong 所属信息详情
     * @Title select
     * @Intro 获取所属信息详情
     * @Date 2024-08-15 17:58:06.881
     */
    public BelongDO select(Long id) {
        return belongService.getById(id);
    }

    /**
     * @param belong 所属信息
     * @Title create
     * @Intro 创建所属信息
     * @Date 2024-08-15 17:58:06.881
     */
    public Long create(BelongDO belong) {
        Assert.isTrue(belongService.create(belong), "新增失败");
        return belong.getBelongId();
    }

    /**
     * @param belong 所属信息
     * @Title update
     * @Intro 更新所属信息
     * @Date 2024-08-15 17:58:06.881
     */
    public void update(BelongDO belong) {
        Assert.isTrue(belongService.update(belong), "修改失败");
    }

    /**
     * @param ids 所属信息ID数组
     * @Title delete
     * @Intro 删除所属信息
     * @Date 2024-08-15 17:58:06.881
     */
    public void delete(Long... ids) {
        Assert.isTrue(belongService.delete(Arrays.asList(ids)), "删除失败");
    }

    /**
     * 所属单位树
     *
     * @param require
     * @return
     */
    public List<TreeVO> belongTree(Integer require) {
        LoginInfo user = tokenService.getUser();
        Long belongId = user.getBelongId();
        String userType = user.getUserType();

        logs.info("【用户信息】所属ID:{}", belongId);
        logs.info("【用户信息】用户类型:{}", userType);
        List<BelongDO> belongList;
        if (Objects.equals(UserType.AGENT.getCode(), userType)) {
            belongList = belongService.listByPid(UserType.SITE.getCode(), belongId);
        } else {
            belongList = belongService.list();
        }
        //当前角色所属信息
        BelongDO selfBelong = belongService.getById(belongId);
        Assert.isTrue(BeanUtils.isNotNull(selfBelong), "未找到当前用户所属信息");

        TreeVO treeVO = new TreeVO();
        BeanUtils.clone(selfBelong, treeVO);
        //将当前用户放在首条
        List<TreeVO> voList = new ArrayList<>();
        voList.add(treeVO);

        //如果是代理并且需要平台信息
        if (Objects.equals(UserType.AGENT.getCode(), userType) && Objects.equals(LogicCode.YES, require)) {
            BelongDO platform = belongService.getById(1L);

            TreeVO platformVO = new TreeVO();
            BeanUtils.clone(platform, platformVO);
            voList.add(platformVO);
        }

        Map<Long, List<TreeVO>> siteMap = new HashMap<>();

        for (BelongDO b : belongList) {
            String belongType = b.getBelongType();
            TreeVO vo = new TreeVO();
            BeanUtils.clone(b, vo);
            if (Objects.equals(UserType.AGENT.getCode(), belongType)) {
                voList.add(vo);
            } else if (Objects.equals(UserType.SITE.getCode(), belongType)) {
                Long parentId = b.getParentId();
                if (siteMap.containsKey(parentId)) {
                    List<TreeVO> vList = siteMap.get(parentId);
                    vList.add(vo);
                    siteMap.put(parentId, vList);
                } else {
                    List<TreeVO> treeList = new ArrayList<>();
                    treeList.add(vo);
                    siteMap.put(parentId, treeList);
                }
            }
        }

        for (TreeVO treeVo : voList) {
            Long agentBelongId = treeVo.getBelongId();
            if (siteMap.containsKey(agentBelongId)) {
                treeVo.setList(siteMap.get(agentBelongId));
            }
        }

        return voList;
    }

    /**
     * @param menuIds
     * @Title setHomeMenu
     * @Desc 设置所属菜单权限
     * @Date 2024-09-05 09:23:33.569
     */
    @Transactional
    public void setHomeMenu(Long... menuIds) {
        if (BeanUtils.isNull(menuIds)) return;

        LoginInfo user = tokenService.getUser();

        Long userId = user.getUserId();
        Long belongId = user.getBelongId();
        logs.info("【设置所属菜单】用户ID:{}", userId);
        logs.info("【设置所属菜单】所属ID:{}", belongId);

        List<ShortCutVO> ordinalList = shortCutService.listByUserId(userId, null);

        // 关闭所有菜单
        ShortCutMenuDO closeParam = new ShortCutMenuDO();
        closeParam.setUserId(userId);
        closeParam.setStatus(LogicCode.NO);
        shortCutService.update(closeParam);

        Map<Long, ShortCutVO> map = new HashMap<>();
        for (ShortCutVO shortCutVO : ordinalList) {
            map.put(shortCutVO.getMenuId(), shortCutVO);
        }

        List<ShortCutMenuDO> updateList = new ArrayList<>();
        List<ShortCutMenuDO> createList = new ArrayList<>();

        for (Long menuId : menuIds) {
            ShortCutMenuDO shortCutMenu = new ShortCutMenuDO();
            shortCutMenu.setUserId(userId);
            shortCutMenu.setMenuId(menuId);
            shortCutMenu.setStatus(LogicCode.YES);
            if (map.containsKey(menuId)) {
                updateList.add(shortCutMenu);
            } else {
                shortCutMenu.setUserId(userId);
                shortCutMenu.setBelongId(belongId);
                createList.add(shortCutMenu);
            }
        }
        // 开启
        for (ShortCutMenuDO update : updateList) {
            shortCutService.updateByMenuIdAndUserId(update.getMenuId(), update.getUserId());
        }

        // 新增
        for (ShortCutMenuDO create : createList) {
            Assert.isTrue(shortCutService.create(create), "新增失败");
        }

    }

    /**
     * @Title getHomeMenu
     * @Desc 获取快捷菜单
     * @Date 2024-09-05 14:50:25.628
     * @Return List<ShortCutVO>
     */
    public List<ShortCutVO> getHomeMenu() {
        LoginInfo user = tokenService.getUser();

        Long userId = user.getUserId();
        Long belongId = user.getBelongId();
        logs.info("【获取快捷菜单】用户ID:{}", userId);
        logs.info("【获取快捷菜单】所属ID:{}", belongId);

        String shortcut = "xxx";
        logs.info("[快捷菜单]：{}", shortcut);
        return shortCutService.listByUserId(userId, LogicCode.YES);
    }

    /**
     * @param param
     * @Title walletList
     * @Desc 查询钱包列表
     * @Date 2024-10-26 09:51:45.245
     * @Return List<WalletVO>
     */
//    public List<BelongStatisticsVO> walletList(WalletParam param) {
//        BelongParam belong = new BelongParam();
//        BeanUtils.clone(param, belong);
//        return belongService.searchBelong(belong);
//
////        Map<Long, Long> siteMap = belongConsumer.containerNums("belong_id");
////        Map<Long, Long> agentMap = belongConsumer.containerNums("agent_id");
////
////        List<BelongVO> voList = new ArrayList<>();
////        for (BelongVO b : list) {
////            // 去除平台
////            if (Objects.equals(RoleTypes.ADMIN.getCode(), b.getBelongType())) {
////                continue;
////            }
////            BelongVO vo = new BelongVO();
////            BeanUtils.clone(b, vo);
////            if (siteMap.containsKey(b.getBelongId())) {
////                vo.setContainerNums(siteMap.get(b.getBelongId()));
////            } else if (agentMap.containsKey(b.getAgentId()) && Objects.equals(RoleTypes.AGENT.getCode(), b.getBelongType())) {
////                vo.setContainerNums(agentMap.get(b.getAgentId()));
////            } else {
////                vo.setContainerNums(0L);
////            }
////            voList.add(vo);
////        }
////
////        return voList;
//    }

    /*-----------------------------------------------匹配搜索----------------------------------------------------*/

    /**
     * @Title searchBelongName
     * @Desc 所属名称匹配搜索
     * @Date 2024-09-14 14:27:57.625
     * @Return List<String>
     */
    public List<String> searchBelongName(String belongName) {
        BelongSearchParam param = new BelongSearchParam();
        param.setBelongName(belongName);
        LoginInfo user = tokenService.getUser();
        String userType = user.getUserType();
        Long belongId = user.getBelongId();
        logs.info("【所属名称匹配搜索】用户类型:{}", userType);
        logs.info("【所属名称匹配搜索】所属ID:{}", belongId);
        if (Objects.equals(UserType.AGENT.getCode(), userType)) {
            param.setParentId(belongId);
        }
        if (Objects.equals(UserType.SITE.getCode(), userType)) {
            param.setBelongId(belongId);
        }
        param.setSearchField("b.belong_name");
        List<String> list = belongService.searchTableField(param);
        return BeanUtils.isNotNull(list) ? list : new ArrayList<>();
    }

    public List<String> searchPhoneNumber(String phoneNumber) {
        BelongSearchParam param = new BelongSearchParam();
        param.setPhoneNumber(phoneNumber);
        param.setSearchField("usr.user_name");
        List<String> list = belongService.searchTableField(param);
        return BeanUtils.isNotNull(list) ? list : new ArrayList<>();
    }

    public List<BelongDO> search(BelongPageParam belong) {
        return belongService.search(belong);
    }
}
